/**
 * @name XLSXView
 * @desc
 * @author
 * @date
 */
import React, { Component } from "react";
import { xlsxData } from "./datas";
import XLSX from "xlsx";
import styles from "./styles.module.less";

class XLSXView extends Component {
  state = {
    type: 0,
    sheetList: []
  };
  componentDidMount() {
    this.init();
  }
  /**
   * @name init
   * @description 初始化表格数据
   */
  init = (val) => {
    const { type } = this.state;
    let workbook = val ? val : xlsxData();
    console.log("workbook==000=", workbook);

    let sheetList = [];
    let persons = [];
    // 表格的表格范围，可用于判断表头是否数量是否正确
    let fromTo = "";
    // 遍历每张表读取
    if (!workbook.Sheets) {
      return;
    }
    for (let sheet in workbook.Sheets) {
      if (workbook.Sheets.hasOwnProperty(sheet)) {
        // fromTo = workbook.Sheets[sheet]['!ref'] //判断表头的数量，就需要使用到!ref属性
        sheetList.push(sheet);
        // persons = persons.concat(XLSX.utils.sheet_to_html(workbook.Sheets[sheet]))
        // break // 如果只取第一张表，就取消注释这行
      }
    }
    this.setState({ sheetList });
    persons = persons.concat(XLSX.utils.sheet_to_html(workbook.Sheets[sheetList[type]]));

    console.log("persons=====", persons);
    document.getElementById("demo").innerHTML = persons;
  };
  /**
   * @name typeChange
   * @param type number 下标
   */
  typeChange = (type) => {
    this.setState({ type }, () => {
      this.init();
    });
  };
  xlsx;

  /**

   \* @name files

   */

  files = (e) => {
    if (!e) {
      return;
    }
    console.log("files===", e);
    let rABS = false; //是否将文件读取为二进制字符串
    let that = this;
    let workbook = ""; //读取完成的数据
    let persons = [];
    let files = e && e.target.files;
    // let f = Object.files[0];
    let f = files[0];
    let fileReader = new FileReader();
    fileReader.onload = function (e) {
      try {
        let data = e.target.result;
        if (rABS) {
          workbook = XLSX.read(btoa(that.fixdata(data)), {
            //手动转化
            type: "base64"
          });
        } else {
          workbook = XLSX.read(data, {
            type: "binary"
          });
        }
        //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
        //wb.Sheets[Sheet名]获取第一个Sheet的数据
        console.log("二进制流方式===", JSON.stringify(workbook), persons);
      } catch (e) {
        console.log("文件类型不正确");
        return;
      }

      // 表格的表格范围，可用于判断表头是否数量是否正确
      let fromTo = "";
      let sheetList = [];
      // 遍历每张表读取
      for (let sheet in workbook.Sheets) {
        if (workbook.Sheets.hasOwnProperty(sheet)) {
          // fromTo = workbook.Sheets[sheet]['!ref'] //判断表头的数量，就需要使用到!ref属性
          sheetList.push(sheet);
          console.log("80=========", fromTo, sheetList);
          // persons = persons.concat(XLSX.utils.sheet_to_html(workbook.Sheets[sheet]))
          persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
          // break // 如果只取第一张表，就取消注释这行
        }
      }
      persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheetList[1]]));
      console.log("persons=====", persons);
      document.getElementById("demo").innerHTML = JSON.stringify(persons);
      //行数
      console.log(workbook.SheetNames.length);
    };
    // 以二进制方式打开文件
    // fileReader.readAsBinaryString(files[0])
    if (rABS) {
      fileReader.readAsArrayBuffer(f);
    } else {
      fileReader.readAsBinaryString(f);
    }
  };

  render() {
    const { sheetList = [], type } = this.state;
    return (
      <div>
        <div style={{ padding: "20px" }}>
          {sheetList instanceof Array &&
            sheetList.length > 0 &&
            sheetList.map((item, index) => (
              <div key={index} className={`${styles.type} ${index === type ? styles.type_active : null}`} onClick={() => this.typeChange(index)}>
                {item}
              </div>
            ))}
        </div>
        <input type="file" name="xlfile" accept=".xlsx" id="xlf" onChange={this.files} />
        <div id="demo" className={styles.demo}></div>
      </div>
    );
  }
}
export default XLSXView;
